const express=require("express")
const singleuploads=express.Router();
const path = require("path")
const fs=require("fs")
const multer = require("multer")
const moment = require('moment');
const localhost='http://49.235.166.90:5055/'
// const localhost='http://localhost:5055/'
const {recommendTable:singlebase}=require('../database/singlebase')
var upload = multer({ dest: 'pub/' })


singleuploads.post('/', upload.single('imgs1'), function (req, res, next) {
    // console.log("single");
    // console.log(req.file);
    console.log(req.body);
    console.log(req.file);
    if (!req.file){
        res.send({
            code:5000,
            msg:'图片未上传'
        })
    }

    let imgxx={}
    const file=req.file;
    //获取后缀名
    const extname = path.extname(file.originalname)
    //获取上传成功之后的文件路径
    const filepath = file.path
    //上传之后文件的名称
    const filename = filepath + extname
  
    //重命名，借用fs的rename重命名的方法，第一参数是源文件地址路径，第二个参数是将源文件改名后的地址(和参数一地址相同，只不过名字变了而已，两个参数都是地址)
    fs.rename(filepath,filename,err=>{
        if(err) throw err

        imgxx.bgc=req.body.bgc// 背景颜色
        imgxx.size=req.body.size// 尺寸
        imgxx.imgUrl=`${localhost}${file.filename}${extname}`//图片路径
        imgxx.dataTime=moment().format('YYYY-MM-DD HH:mm:ss')// 时间戳



        singlebase.create({
            usename:req.body.usename,
            useID:req.body.id,
            imgUrl:`${localhost}${file.filename}${extname}`,
            size:req.body.size,
            bgc:req.body.bgc,
            dataTime:moment().format('YYYY-MM-DD HH:mm:ss'),
            grade:req.body.grade,
            college:req.body.college,
            classes:req.body.classes,
        },(err, doc, len)=>{
            if (err) {
                res.send({
                    code:5000,
                    msg:err
                })
            }else{
                res.send({
                    code:0,
                    msg:doc
                })
            }
        })

    });
  
  });

module.exports=singleuploads